package com.jibei.mendo.utils;

import android.text.TextUtils;

/**
 * Created by lhl on 2019/9/5.
 */
public class TimeUtil {

    private TimeUtil() {
    }

    public static TimeUtil getInstance() {
        return TimeUtil.Holder.instance;
    }

    private static class Holder {
        private static final TimeUtil instance = new TimeUtil();
    }

    /**
     * 时间转毫秒数
     *
     * @param originalTime eg  1:3.108
     * @return 结果
     */
    public synchronized long timeToMillisecond(String originalTime) {
        if (TextUtils.isEmpty(originalTime))
            return 0;

        String hourStr = originalTime.substring(0, 2);//时
        String minStr = originalTime.substring(3, 5);//分
        String secondStr = originalTime.substring(6, 8);//秒
        String milliStr = originalTime.substring(9);//毫秒

        int hourInt = Integer.parseInt(hourStr);
        int minInt = Integer.parseInt(minStr);
        int secondInt = Integer.parseInt(secondStr);
        int milliInt = Integer.parseInt(milliStr);

        long totalMilli = hourInt * 60 * 60 * 1000 + minInt * 60 * 1000 + secondInt * 1000 + milliInt;
//        Log.d("lhl", "   时>>>" + hourStr + "   分>>>" + minStr + "   秒>>>" + secondStr + "   毫秒>>>" + milliStr + "   总毫秒数>>>" + totalMilli);
        return totalMilli;
    }

    /**
     * 毫秒数转时间
     *
     * @param originalTime 毫秒数
     * @return 结果
     */
    public synchronized String millisecondToTime(long originalTime) {
        String hourStr = "00";//时
        String minStr = "00";//分
        String secondStr = "00";//秒
        String milliStr = "000";//毫秒

        if (originalTime > 0) {

            long milli = originalTime % 1000;//毫秒
            milliStr = String.valueOf(milli);
            switch (milliStr.length()) {
                case 1:
                    milliStr = "00" + milliStr;
                    break;
                case 2:
                    milliStr = "0" + milliStr;
                    break;
                default:
                    break;
            }

            long second = ((originalTime - milli) / 1000) % 60;//秒
            secondStr = String.valueOf(second);
            if (secondStr.length() == 1) {
                secondStr = "0" + secondStr;
            }

            long min = ((originalTime - milli - second) / 60000) % 60;//分
            minStr = String.valueOf(min);
            if (minStr.length() == 1) {
                minStr = "0" + minStr;
            }

            long hour = ((originalTime - milli - second - min) / 3600000) % 24;//时
            hourStr = String.valueOf(hour);
            if (hourStr.length() == 1) {
                hourStr = "0" + hourStr;
            }
        }
//        Log.i("lhl", hourStr + ":" + minStr + ":" + secondStr + "." + milliStr);
        return hourStr + ":" + minStr + ":" + secondStr + "." + milliStr;
    }
}


